package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;
    //阻塞队列 存储订单对象

    private static final DefaultRedisScript<Long> DEFAULT_SCRIPT;

    //创建一个异步的线程池
    private static final ExecutorService SECkILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    //获取代理对象
    private IVoucherOrderService voucherOrderService;

    //创建一个方法使该方法在当前类初始化完成后就开始执行线程池中的任务
    @PostConstruct
    private void init(){
        SECkILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }



    private class VoucherOrderHandler implements Runnable {

         String QueueName = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    //从redis stream消息队列中读取消息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2L)),
                            StreamOffset.create(QueueName, ReadOffset.lastConsumed()));

                    if (list.isEmpty() || list == null || list.isEmpty()) {
                        continue;
                    }

                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();

                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value,
                            new VoucherOrder(),
                            true);
                    handleVoucherOrder(voucherOrder);

                    stringRedisTemplate.opsForStream().acknowledge(QueueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常:{}",e.getMessage());
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        while (true) {
            try {
                //从redis stream消息队列中读取消息
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create("stream.orders", ReadOffset.from("0")));

                if (list.isEmpty() || list == null || list.isEmpty()) {
                    continue;
                }

                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();

                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value,
                        new VoucherOrder(),
                        true);
                handleVoucherOrder(voucherOrder);

                stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
            } catch (Exception e) {
                log.error("处理pendingList订单异常:{}", e.getMessage());
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    //创建一个内部类实现runable接口重写run方法进行异步处理的业务
//    private BlockingQueue<VoucherOrder> OrderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    VoucherOrder voucherOrder = OrderTasks.take();
//                    handleVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("处理订单异常:{}",e.getMessage());
//                }
//            }
//        }
//    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //1.获取锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //2.尝试获取锁
        boolean tryLock = lock.tryLock();
        if (!tryLock) {
            log.error("不允许重复下单");
            return;
        }
        try {
             voucherOrderService.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }
    }

    static {
        DEFAULT_SCRIPT = new DefaultRedisScript<>();
        DEFAULT_SCRIPT.setResultType(Long.class);
        DEFAULT_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
    }

    @Override
    public Result addVoucherOreder(Long voucherId) {
        //1.从数据库获取订单信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //2.判断有效时间是否开始或结束
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀活动尚未开始");
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀活动已结束");
        }
        Long userId = UserHolder.getUser().getId();
        Long execute = stringRedisTemplate.execute(DEFAULT_SCRIPT,
                Collections.emptyList(), voucherId.toString(), userId.toString(),redisIdWorker.nextId("order").toString());
        if (execute.intValue() != 0){
            Result.fail(execute == 1 ? "库存不足" : "您已下单");
        }
        Long orderId = redisIdWorker.nextId("order");
        // 创建优惠卷订单对象存入阻塞队列
//        VoucherOrder voucherOrder = VoucherOrder.builder()
//                .voucherId(voucherId)
//                .id(orderId)
//                .userId(userId)
//                .build();
        // 将新建订单对象添加到阻塞队列进行异步处理
//        OrderTasks.add(voucherOrder);
        voucherOrderService  = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }

//    @Override
//    public Result addVoucherOreder(Long voucherId) {
//        //1.从数据库获取订单信息
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //2.判断有效时间是否开始或结束
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀活动尚未开始");
//        }
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀活动已结束");
//        }
//        //3.判断秒杀卷是否还有库存
//        if (seckillVoucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
////        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
////        boolean isLock = lock.tryLcok(120L);
//        //1.获取锁对象
//        RLock Lock = redissonClient.getLock("anyLock");
//        //2.尝试获取锁
//        boolean tryLock = Lock.tryLock();
//        if (!tryLock) {
//            return Result.fail("不允许重复下单");
//        }
//        try {
//            IVoucherOrderService voucherOrderService = (IVoucherOrderService) AopContext.currentProxy();
//            return voucherOrderService.createVoucherOrder(voucherId);
//        }finally {
//            Lock.unlock();
//        }
//    }
    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //从ThreadLocal中获取当前登录用户id
        Long id = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", id).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            log.error("您已购买一次");
            return;
        }
        //4.扣减库存
        boolean update = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();
        if (!update) {
            log.error("库存不足");
            return;
        }
        save(voucherOrder);

    }
}
